<template>
  <WujieVue
    width="100%"
    height="100%"
    :key="appId"
    :name="appId"
    :alive="true"
    :url="appUrl"
    :sync="true"
    :fetch="handleFetch"
  ></WujieVue>
</template>

<script>
import { mapState } from 'vuex'
import WujieVue from 'wujie-vue2'

const { destroyApp } = WujieVue
const presetRoutes = ['wallboard', 'applications', 'journal']
const appUrlMap = {
  wallboard: `${window.location.origin}/springbootadmin/wallboard`,
  applications: `${window.location.origin}/springbootadmin/applications`,
  journal: `${window.location.origin}/springbootadmin/journal`,
  // wallboard: 'http://localhost:8080/wallboard',
  // applications: 'http://localhost:8080',
  // journal: 'http://localhost:8080/journal',
}

export default {
  name: 'wujie',
  props: {
    appId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      appUrlMap,
      presetRoutes,
    }
  },
  computed: {
    ...mapState($moduleName, ['currentPageCode', 'cachePage']),
    appUrl() {
      const { appId, appUrlMap } = this
      this.$options.name = appId
      return appUrlMap[appId]
    }
  },
  watch: {
    currentPageCode(newVal, oldVal) {
      if (newVal !== oldVal) {
        const { presetRoutes, cachePage } = this
        const closePage = presetRoutes.filter(r => !cachePage.includes(r))
        for (const appName of closePage) {
          destroyApp(appName)
        }
      }
    }
  },
  methods: {
    handleFetch(url, options) {
      const auth = localStorage.Authorization
      const authorization = auth ? 'Bearer ' + auth : ''
      let headers = { authorization }
      if (options && options.headers) {
        headers = Object.assign(
          {},
          options.headers,
          { authorization }
        )
      }
      return window.fetch(url, {
        ...options,
        headers
      })
    },
    resetUrlQuery() {
      const url = new URL(window.location.href)
      url.search = ''
      window.history.replaceState(null, '', url.href)
    },
    destroyAllApp() {
      destroyApp('wallboard')
      destroyApp('applications')
      destroyApp('journal')
    }
  },
  mounted() {
    this.resetUrlQuery()
  },
  beforeDestroy() {
    this.destroyAllApp()
  }
}
</script>
